#!/bin/bash

echo "Usage: $0 [event_file] [[repeat_times]]"

me="${BASH_SOURCE[0]}"
SCRIPT_LOC=$(cd $(dirname `[ -L $me ] && readlink $me || echo $me`) && pwd -P)
ADB="adb"

if [ $# -ne 0 ]; then
    PRE_CHOICE=$1
    PRE_TIMES=$2
fi

$ADB root || exit
$ADB wait-for-device
sleep 1

BIN_DIR=/data/local/tmp
EVENTS_DIR=/data/local/tmp/evs
EVENT_FILE=""   #recorded or selected event file
PREFIX=_myevents

$ADB shell mkdir -p $EVENTS_DIR || exit

$ADB push $SCRIPT_LOC/sendevent_finalx $BIN_DIR/ || exit
$ADB push $SCRIPT_LOC/getevent_finalx $BIN_DIR/ || exit

$ADB shell chmod 777 $BIN_DIR/sendevent_finalx || exit
$ADB shell chmod 777 $BIN_DIR/getevent_finalx || exit

function on_done() {
    echo "... on_done ..."
    local arr_pids=($($ADB shell ps | grep -E "$BIN_DIR/(send|get)event_finalx" | awk '{print $2}'))
    if [ ${#arr_pids[@]} -gt 0 ]; then
        $ADB shell kill ${arr_pids[@]}
    fi
    #$ADB shell umount $CACHED_DIR > /dev/null 2>&1
    exit
}

trap 'on_done' SIGINT SIGTERM EXIT

array_events=($($ADB shell "ls $EVENTS_DIR" | grep "$PREFIX.*" | tr -d '\r'))
array_count=${#array_events[@]}
hint_select=""
if [ $array_count -gt 0 ]; then
    echo -e "\nEvents already exists:"
    echo "----------------------"
    for i in ${array_events[@]}; do
        echo "$i"
    done
    echo "----------------------"
    hint_select="[Select EventsName] or "
fi

echo -en "\n${hint_select}[Press Enter to Start a New Recording] ...> "
if [ -n "$PRE_CHOICE" ]; then
    choice=$PRE_CHOICE
    echo $choice
else
    read choice
fi

EVENT_FILE=$EVENTS_DIR/$PREFIX.$(date +%Y%m%d_%H%M%S)
found=false
for i in ${array_events[@]}; do 
    if [ "$choice" = "$i" ]; then
        found=true
        EVENT_FILE="$EVENTS_DIR/$choice"
        break
    fi
done

if [ $found = false ]; then
    $ADB shell $BIN_DIR/getevent_finalx -o $EVENT_FILE > /dev/null &
    pid_bg=$!

    echo -e "\nStart New Recording ..."
    echo -n "Press Ctrl-D or Enter to stop ...> "
    read stop

    kill -9 $pid_bg > /dev/null 2>&1
fi

echo -en "\nHow many times to repeat? ...> "
if [ -n "$PRE_TIMES" ]; then
    times=$PRE_TIMES
    echo "$times"
else
    read times
fi
echo "$times" | grep -qEo '^[1-9][0-9]*$' || exit

count=1
while [ $count -le $times ]; do 
    echo "$(($times - $count)) times left"
    $ADB shell $BIN_DIR/sendevent_finalx $EVENT_FILE || exit

    ((count ++))
    sleep 1
done
